import { PLAY_MODE } from "@/assets/js/constant";
import { shuffle } from "@/assets/js/func";
// import { findIndex } from "core-js/core/array";
export function selectPlay({ commit }, { list, index }) {
  commit("setPlayMode", PLAY_MODE.sequence);
  commit("setSequenceList", list);
  commit("setPlayingState", true);
  commit("setFullScreen", true);
  commit("setPlayList", list);
  commit("setCurrentIndex", index);
}

export function randomPlay({ commit }, list) {
  commit("setPlayMode", PLAY_MODE.random);
  commit("setSequenceList", list);
  commit("setPlayingState", true);
  commit("setFullScreen", true);
  commit("setPlayList", shuffle(list));
  commit("setCurrentIndex", 0);
}
export function changeMode({ commit, state, getters }, mode) {
  const currentId = getters.currentSong.id;
  if (mode === PLAY_MODE.random) {
    //随机播放
    commit("setPlayList", shuffle(state.sequenceList));
  } else {
    //顺序播放
    commit("setPlayList", state.sequenceList);
  }
  const index = state.playList.findIndex((item) => {
    return item.id == currentId;
  });
  commit("setCurrentIndex", index);
  commit("setPlayMode", mode);
}
//移除歌曲
export function removeSong({ commit, state }, song) {
  const sequenceList = state.sequenceList.slice();
  const playList = state.playList.slice();
  const sequenceIndex = findIndex(sequenceList, song);
  const playIndex = findIndex(playList, song);
  if (sequenceIndex < 0 || playIndex < 0) {
    return;
  }

  sequenceList.splice(sequenceIndex, 1);
  playList.splice(playIndex, 1);

  let currentIndex = state.currentIndex;
  if (playIndex < currentIndex || currentIndex === playList.length) {
    currentIndex--;
  }
  commit("setSequenceList", sequenceList);
  commit("setPlayList", playList);
  commit("setCurrentIndex", currentIndex);
  if (!playList.length) {
    commit("setPlayingState", false);
  }
}
//添加歌曲
export function addSong({ commit, state }, song) {
  const playList = state.playList.slice();
  const sequenceList = state.sequenceList.slice();
  let currentIndex = state.currentIndexs;
  const playIndex = findIndex(playList, song);
  if (playIndex > -1) {
    currentIndex = playIndex;
  } else {
    playList.push(song);
    currentIndex = playList.length - 1;
  }
  const sequenceIndex = findIndex(sequenceList, song);
  if (sequenceIndex == -1) {
    sequenceList.push(song);
  }
  commit("setSequenceList", sequenceList);
  commit("setPlayingState", true);
  commit("setFullScreen", true);
  commit("setPlayList", playList);
  commit("setCurrentIndex", currentIndex);
}

function findIndex(list, song) {
  return list.findIndex((item) => {
    return item.id === song.id;
  });
}
